<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/Reports' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card class="box-card" style="margin-top: 20px">
      <el-button type="primary" @click="addRole">添加角色</el-button>
      <!-- 树形表格 -->
      <el-table :data="tableData" style="width: 100%">
        <el-table-column type="expand">
          <template slot-scope="scope">
            <div style="width: 90%; margin: auto">
              <!-- 渲染一级权限 -->
              <el-row
                v-for="(item, index) in scope.row.children"
                :key="index"
                :class="['bttom', index === 0 ? 'top' : '', 'vacenter']"
              >
                <el-col :span="8">
                  <el-tag closable @close="handleClose(scope.row, item.id)">
                    {{ item.authName }}
                  </el-tag>
                  <i class="el-icon-caret-right"></i>
                </el-col>
                <el-col :span="16">
                  <!-- 二级权限 -->
                  <el-row
                    v-for="(value, key) in item.children"
                    :key="key"
                    :class="[key === 0 ? '' : 'top', , 'vacenter']"
                  >
                    <el-col :span="8">
                      <el-tag
                        closable
                        type="success"
                        @close="handleClose(scope.row, value.id)"
                      >
                        {{ value.authName }}
                      </el-tag>
                      <i class="el-icon-caret-right"></i>
                    </el-col>
                    <!-- 三级权限 -->
                    <el-col :span="16">
                      <el-tag
                        v-for="(data, idx) in value.children"
                        :key="idx"
                        closable
                        type="warning"
                        @close="handleClose(scope.row, data.id)"
                      >
                        {{ data.authName }}
                      </el-tag>
                    </el-col>
                  </el-row>
                </el-col>
              </el-row>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="索引" type="index"> </el-table-column>
        <el-table-column label="角色名称" prop="roleName"> </el-table-column>
        <el-table-column label="角色描述" prop="roleDesc"> </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="edit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="del(scope.row.id)"
              >删除</el-button
            >
            <el-button
              type="warning"
              icon="el-icon-setting"
              size="mini"
              @click="grant(scope.row)"
              >分配权限</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 弹出的模态框 -->
      <el-dialog
        :title="dialog.title"
        :visible.sync="dialogVisible"
        width="50%"
      >
        <el-form
          :model="ruleForm"
          :rules="rules"
          ref="ruleForm"
          label-width="100px"
          class="demo-ruleForm"
        >
          <el-form-item label="角色名称" prop="roleName">
            <el-input v-model="ruleForm.roleName"></el-input>
          </el-form-item>
          <el-form-item label="角色描述" prop="roleDesc">
            <el-input v-model="ruleForm.roleDesc"></el-input>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="adding"
            v-if="dialog.type == 'adding'"
            >添加</el-button
          >
          <el-button type="primary" @click="editAdd" v-else>编辑</el-button>
        </span>
      </el-dialog>
      <!-- 分配权限的模态框 -->
      <el-dialog title="分配权限" :visible.sync="dialogVisible1" width="50%">
        <el-tree
          :data="dataList"
          show-checkbox
          node-key="id"
          :default-checked-keys="checkNode"
          :props="defaultProps"
          default-expand-all
          ref="tree"
        >
        </el-tree>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible1 = false">取 消</el-button>
          <el-button type="primary" @click="limits">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "MyVueRoles",

  data() {
    return {
      // 角色列表的数据
      tableData: [],
      // 弹出模态框的表示
      dialogVisible: false,
      dialogVisible1: false,
      rules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "角色描述不能为空", trigger: "blur" },
          {
            min: 5,
            max: 10,
            message: "长度在 5 到 10 个字符",
            trigger: "blur",
          },
        ],
      },
      ruleForm: {
        roleName: "",
        roleDesc: "",
      },
      dialog: {
        title: "",
        type: "adding",
      },
      // 所有权限的数据
      dataList: [],
      defaultProps: {
        label: "authName",
        children: "children",
      },
      // 默认勾选的节点
      checkNode: [],
      // 角色id
      roleId: "",
    };
  },

  mounted() {
    this.list();
  },

  methods: {
    // 渲染
    list() {
      this.$http.get("roles").then((res) => {
        this.tableData = res.data.data;
      });
    },
    // 点击标签移除权限
    handleClose(row, rolesId) {
      this.$confirm("此操作将移除权限, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete(`roles/${row.id}/rights/${rolesId}`).then((res) => {
            if (res.data.meta.status === 200) {
              this.$message.success(res.data.meta.msg);
              row.children = res.data.data;
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 添加角色
    addRole() {
      this.ruleForm = {};
      this.dialog.title = "添加角色";
      this.dialogVisible = true;
    },
    adding() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) {
          this.$message("信息填写不正确");
        } else {
          this.$http.post(`roles`, this.ruleForm).then((res) => {
            if (res.data.meta.status === 201) {
              this.$message.success(res.data.meta.msg);
              this.dialogVisible = false;

              this.list();
            } else {
              this.$message.error(res.data.meta.msg);
            }
          });
        }
      });
    },
    // 删除角色
    del(id) {
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete(`roles/${id}`).then((res) => {
            console.log(res);
            if (res.data.meta.status === 200) {
              this.$message.success(res.data.meta.msg);
         this.list()
            } else {
              this.$message.error(res.data.meta.msg);
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    // 编辑回填
    edit(row) {
      this.dialogVisible = true;
      this.dialog.title = "编辑角色";
      this.dialog.type = " editAdd";
      this.ruleForm = row;
    },
    editAdd() {
      this.$http.put(`roles/${this.ruleForm.id}`, this.ruleForm).then((res) => {
        if (res.data.meta.status === 200) {
          this.$message.success("编辑成功");
          this.list();
          this.dialogVisible = false;
        } else {
          this.$message.error(res.data.meta.msg);
        }
      });
    },
    // 点击分配权限拿到数据
    grant(row) {
      this.roleId = row.id;
      this.dialogVisible1 = true;
      this.$http.get(`rights/tree`).then((res) => {
        if (res.data.meta.status === 200) {
          this.dataList = res.data.data;
        }
        this.recursion(row, this.checkNode);
      });
    },
    // 递归拿最后一层的id
    recursion(row, arr) {
      if (!row.children) {
        return arr.push(row.id);
      }
      row.children.forEach((item) => this.recursion(item, arr));
    },
    // 角色授权
    limits() {
      let obj = this.$refs.tree
        .getCheckedKeys()
        .concat(this.$refs.tree.getHalfCheckedKeys())
        .join(",");
      this.$http
        .post(`roles/${this.roleId}/rights`, { rids: obj })
        .then((res) => {
          if (res.data.meta.status === 200) {
            this.$message.success(res.data.meta.msg);
            this.dialogVisible1=false
            this.list()
          }else{
            this.$message.error(res.data.meta.msg)
          }
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.el-tag {
  margin: 20px;
}
.top {
  border-top: 1px solid gainsboro;
}
.bttom {
  border-bottom: 1px solid gainsboro;
}
.vacenter {
  display: flex;
  align-items: center;
}
</style>